package com.imonsoft.sqm.service.sys;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.util.ListUtil;
import com.imonsoft.common.util.StringUtil;
import com.imonsoft.sqm.dao.sys.FunctionDAO;
import com.imonsoft.sqm.dao.sys.RoleDAO;
import com.imonsoft.sqm.dao.sys.RoleFunctionDAO;
import com.imonsoft.sqm.pojo.sys.Function;
import com.imonsoft.sqm.pojo.sys.FunctionExample;
import com.imonsoft.sqm.pojo.sys.Role;
import com.imonsoft.sqm.pojo.sys.RoleExample;
import com.imonsoft.sqm.pojo.sys.RoleFunction;
import com.imonsoft.sqm.pojo.sys.RoleFunctionExample;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private RoleDAO roleDAO;
	@Autowired
	private RoleFunctionDAO roleFunctionDAO;
	@Autowired
	private FunctionService functionService;
	@Autowired
	private FunctionDAO functionDAO;

	@Override
	public void deleteRole(List<Long> idList) {
		if (null == idList || idList.isEmpty()) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		for (Long id : idList) {
			deleteRoleFunctionByRoleId(id);
			roleDAO.deleteRoleByPrimaryKey(id);
		}
	}

	@Override
	public List<Role> findRoleByCode(String code) {
		if (StringUtils.isEmpty(code)) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		RoleExample example = new RoleExample();
		RoleExample.Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(code)) {
			criteria.andCodeEqualTo(code);
		}
		List<Role> roleList = roleDAO.selectRoleByExample(example);
		return roleList;
	}

	@Override
	public Long insert(Role entity) {
		if (null == entity) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		entity.setState(ConstantSqm.STATUS_NORMAL);
		Long roleId = roleDAO.insertRole(entity);
		// 进行保存权限
		List<RoleFunction> roleFunctions = new ArrayList<RoleFunction>();
		if (!StringUtil.isBlank(entity.getAuthorityText())) {
			List<String> authoritys = StringUtil.splitToStringList(entity.getAuthorityText());
			for (String code : authoritys) {
				Function function = ListUtil.getSingleResult(functionService.findFunctionByCode(code));
				RoleFunction roleFunction = new RoleFunction();
				roleFunction.setRoleId(roleId);
				roleFunction.setFunctionId(function.getId());
				roleFunction.setState(ConstantSqm.STATUS_NORMAL);
				roleFunctions.add(roleFunction);
			}
		}
		for (RoleFunction roleFunction : roleFunctions) {
			roleFunctionDAO.insertRoleFunction(roleFunction);
		}
		return roleId;
	}

	@Override
	public int update(Role entity) {
		if (null == entity || null == entity.getId()) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		Role role = roleDAO.selectRoleByPrimaryKey(entity.getId());

		RoleFunctionExample example = new RoleFunctionExample();
		RoleFunctionExample.Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(role.getId());
		roleFunctionDAO.deleteRoleFunctionByExample(example);
		// 处理关系表
		List<RoleFunction> roleFunctions = new ArrayList<RoleFunction>();
		if (!StringUtil.isBlank(entity.getAuthorityText())) {
			List<String> authoritys = StringUtil.splitToStringList(entity.getAuthorityText());
			for (String code : authoritys) {
				Function function = ListUtil.getSingleResult(functionService.findFunctionByCode(code));
				RoleFunction roleFunction = new RoleFunction();
				roleFunction.setRoleId(entity.getId());
				roleFunction.setFunctionId(function.getId());
				roleFunction.setState(ConstantSqm.STATUS_NORMAL);
				roleFunctions.add(roleFunction);
			}
		}
		for (RoleFunction roleFunction : roleFunctions) {
			roleFunctionDAO.insertRoleFunction(roleFunction);
		}
		// 更新
		role.setCode(entity.getCode());
		role.setName(entity.getName());
		return roleDAO.updateRoleByPrimaryKey(role);
	}

	@Override
	public int delete(Long id) {
		if (null == id) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		RoleFunctionExample example = new RoleFunctionExample();
		RoleFunctionExample.Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(id);
		roleFunctionDAO.deleteRoleFunctionByExample(example);

		return roleDAO.deleteRoleByPrimaryKey(id);
	}

	@Override
	public Role get(Long id) {
		if (null == id) {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
		Role role = roleDAO.selectRoleByPrimaryKey(id);
		return role;
	}

	public List<Function> getFunctionListByRoleId(Long roleId) {
		if (null == roleId) {
			return null;
		}
		RoleFunctionExample exampleFunction = new RoleFunctionExample();
		RoleFunctionExample.Criteria criteriaFunction = exampleFunction.createCriteria();
		criteriaFunction.andRoleIdEqualTo(roleId);
		List<RoleFunction> roleFunctions = roleFunctionDAO.selectRoleFunctionByExample(exampleFunction);
		if (roleFunctions == null) {
			return null;
		}
		List<Long> ids = new ArrayList<Long>();
		for (RoleFunction roleFunction : roleFunctions) {
			ids.add(roleFunction.getFunctionId());
		}
		FunctionExample example2 = new FunctionExample();
		FunctionExample.Criteria criteria2 = example2.createCriteria();
		criteria2.andIdIn(ids);
		List<Function> functionList = functionDAO.selectFunctionByExample(example2);
		return functionList;
	}

	public List<Role> getRoleListByFunctionId(Long functionId) {
		if (null == functionId) {
			return null;
		}
		RoleFunctionExample exampleFunction = new RoleFunctionExample();
		RoleFunctionExample.Criteria criteriaFunction = exampleFunction.createCriteria();
		criteriaFunction.andFunctionIdEqualTo(functionId);
		List<RoleFunction> roleFunctions = roleFunctionDAO.selectRoleFunctionByExample(exampleFunction);
		if (roleFunctions == null) {
			return null;
		}
		List<Long> ids = new ArrayList<Long>();
		for (RoleFunction roleFunction : roleFunctions) {
			ids.add(roleFunction.getFunctionId());
		}
		RoleExample example2 = new RoleExample();
		RoleExample.Criteria criteria2 = example2.createCriteria();
		criteria2.andIdIn(ids);
		return roleDAO.selectRoleByExample(example2);
	}

	@Override
	public List<Role> findList(Role entity) {
		RoleExample example = new RoleExample();
		example.setOrderByClause("id desc");
		RoleExample.Criteria criteria = example.createCriteria();
		if (null != entity) {
			if (!StringUtils.isEmpty(entity.getCode())) {
				criteria.andCodeLike(entity.getCode() + "%");
			}
		}
		List<Role> roleList = roleDAO.selectRoleByExample(example);
		if (roleList == null) {
			return roleList;
		}
		for (Role role : roleList) {
			List<Function> functionList = getFunctionListByRoleId(role.getId());
			String authorityText = "";
			if (functionList == null) {
				continue;
			}
			int index = 0;
			for (Function function : functionList) {
				if (index > 10) {
					break;
				}
				authorityText += (function.getText() + ",");
				index++;
			}
			role.setAuthorityText(authorityText);
		}
		return roleList;
	}

	public int deleteRoleFunctionByRoleId(Long roleId) {
		if (roleId == null) {
			return -1;
		}
		RoleFunctionExample example = new RoleFunctionExample();
		RoleFunctionExample.Criteria criteria = example.createCriteria();
		criteria.andRoleIdEqualTo(roleId);
		return roleFunctionDAO.deleteRoleFunctionByExample(example);
	}

	public int deleteRoleFunctionByFunction(Long functionId) {
		if (functionId == null) {
			return -1;
		}
		RoleFunctionExample example = new RoleFunctionExample();
		RoleFunctionExample.Criteria criteria = example.createCriteria();
		criteria.andFunctionIdEqualTo(functionId);
		return roleFunctionDAO.deleteRoleFunctionByExample(example);
	}

	@Override
	public DataGrid<Role> getDataGrid(Role entity, Pager pager) {
		RoleExample example = new RoleExample();
		example.setOrderByClause("id desc");
		RoleExample.Criteria criteria = example.createCriteria();
		if (null != entity) {
			if (!StringUtils.isEmpty(entity.getCode())) {
				criteria.andCodeLike(entity.getCode() + "%");
			}
			if (!StringUtils.isEmpty(entity.getName())) {
				criteria.andNameLike(entity.getName() + "%");
			}
			if (!StringUtils.isEmpty(entity.getState())) {
				criteria.andStateEqualTo(entity.getState());
			}
		}
		DataGrid<Role> dataGrid = roleDAO.getDataGrid(example, pager);
		List<Role> roleList = dataGrid.getRows();
		if (roleList == null) {
			return dataGrid;
		}
		for (Role role : roleList) {
			List<Function> functionList = getFunctionListByRoleId(role.getId());
			String authorityText = "";
			if (functionList == null) {
				continue;
			}
			int index = 0;
			for (Function function : functionList) {
				if (index > 2) {
					authorityText += "..";
					break;
				}
				authorityText += (function.getText() + ",");
				index++;
			}
			role.setAuthorityText(authorityText);
		}
		return dataGrid;
	}
}
